<template>
  <div class="orders-container">
    <!-- 导航栏 -->
    <nav class="navbar">
      <div class="navbar-container">
        <div class="logo" @click="goToHome">QingBook</div>
        <ul class="nav-menu">
          <li 
            class="nav-item" 
            :class="{ active: activeIndex === 1 }"
            @click="goToHome"
          >
            首页
          </li>
          <li 
            class="nav-item"
            :class="{ active: activeIndex === 2 }"
          >
            订单
          </li>
          <li 
            class="nav-item"
            :class="{ active: activeIndex === 3 }"
            @click="goToCart"
          >
            购物车
          </li>
          <li class="nav-item">
            <img class="avatar" :src="user.avatarUrl" alt="用户头像" />
          </li>
        </ul>
      </div>
    </nav>

    <!-- 订单内容 -->
    <div class="orders-content">
      <div class="orders-header">
        <h2>我的订单</h2>
        <div class="order-filter">
          <button 
            class="filter-btn" 
            :class="{ active: filterType === 'all' }"
            @click="filterType = 'all'"
          >
            全部订单
          </button>
          <button 
            class="filter-btn" 
            :class="{ active: filterType === 'completed' }"
            @click="filterType = 'completed'"
          >
            已完成
          </button>
        </div>
      </div>

      <!-- 订单列表 -->
      <div class="orders-list">
        <div v-if="filteredOrders.length === 0" class="empty-orders">
          <div class="empty-icon">📦</div>
          <h3>暂无订单</h3>
          <p>快去选购商品吧！</p>
          <button class="go-shopping-btn" @click="goToHome">去购物</button>
        </div>

        <div v-for="order in filteredOrders" :key="order.id" class="order-item">
          <div class="order-header">
            <div class="order-info">
              <span class="order-time">下单时间：{{ formatDate(order.createTime) }}</span>
              <span class="order-id">订单号：{{ order.id }}</span>
              <span class="shop-name">{{ order.shopName }}</span>
            </div>
            <div class="order-status">
              <span :class="getStatusClass(order.status)">{{ getStatusText(order.status) }}</span>
            </div>
          </div>

          <div class="order-goods">
            <div v-for="item in order.items" :key="item.id" class="goods-item">
              <div class="goods-image">
                <img :src="item.image" :alt="item.title" />
              </div>
              <div class="goods-info">
                <h4 class="goods-title">{{ item.title }}</h4>
                <p class="goods-specs">{{ item.specs }}</p>
                <p class="goods-color">颜色：{{ item.color }}</p>
              </div>
              <div class="goods-price">
                <div class="price-quantity">
                  <span class="current-price">¥{{ item.price.toFixed(2) }}</span>
                  <span class="quantity">x{{ item.quantity }}</span>
                </div>
                <div class="total-price">
                  ¥{{ (item.price * item.quantity).toFixed(2) }}
                </div>
              </div>
            </div>
          </div>

          <div class="order-footer">
            <div class="order-total">
              实付款：<span class="total-amount">¥{{ order.totalAmount.toFixed(2) }}</span>
            </div>
            <div class="order-actions">
              <button 
                v-if="order.status === 'pending_receipt'" 
                class="action-btn confirm-receipt"
                @click="confirmReceipt(order.id)"
              >
                确认收货
              </button>
              <button 
                v-if="order.status !== 'cancelled' && order.status !== 'completed'" 
                class="action-btn after-sales"
                @click="applyAfterSales(order.id)"
              >
                申请售后
              </button>
              <button 
                v-if="order.status === 'completed' || order.status === 'cancelled'" 
                class="action-btn buy-again"
                @click="buyAgain(order)"
              >
                再次购买
              </button>
              <button 
                v-if="order.status === 'pending_payment'" 
                class="action-btn cancel-order"
                @click="cancelOrder(order.id)"
              >
                取消订单
              </button>
              <button 
                v-if="order.status === 'completed' || order.status === 'refunded'" 
                class="action-btn delete-order"
                @click="deleteOrder(order.id)"
              >
                删除订单
              </button>
            </div>
          </div>
          <div v-if="order.expressInfo && order.status !== 'pending_payment' && order.status !== 'cancelled'" class="express-info">
            <h4>快递信息</h4>
            <div class="express-details">
              <p>快递公司：{{ order.expressInfo.company }}</p>
              <p>运单号码：{{ order.expressInfo.number }}</p>
              <p v-if="order.expressInfo.estimatedDelivery">预计送达：{{ formatDate(order.expressInfo.estimatedDelivery) }}</p>
            </div>
          </div>
        </div>
      </div>
    </div>
    <div v-if="showAfterSalesModal" class="after-sales-modal">
      <div class="modal-overlay" @click="showAfterSalesModal = false"></div>
      <div class="modal-content">
        <h3>申请售后</h3>
        <p>请选择售后类型：</p>
        <div class="modal-actions">
          <button 
            class="modal-btn refund" 
            @click="handleRefund"
          >
            退款
          </button>
          <button 
            class="modal-btn return-refund" 
            @click="handleReturnRefund"
          >
            退货退款
          </button>
        </div>
        <button class="modal-close" @click="showAfterSalesModal = false">×</button>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { useAuthStore } from '@/store/auth'
import { 
  HomeIcon, SearchIcon, PlusCircleIcon, 
  MessageCircleIcon, UserIcon, SettingsIcon 
} from 'lucide-vue-next'

const router = useRouter()
const authStore = useAuthStore()

// 用户信息
const user = ref(authStore.user || {
  name: '用户',
  username: 'username',
  avatar: 'https://via.placeholder.com/40'
})

// 响应式数据
const activeIndex = ref(2)
const headerImage = ref('src/assets/header.png')
const filterType = ref('all')
const orders = ref([])
const showAfterSalesModal = ref(false)
const currentOrderId = ref(null)

// 计算属性
const filteredOrders = computed(() => {
  if (filterType.value === 'all') {
    return orders.value
  } else if (filterType.value === 'completed') {
    return orders.value.filter(order => order.status === 'completed')
  }
  return orders.value
})

// 生命周期
onMounted(() => {
  loadOrders()
})

// 方法
const deleteOrder = (orderId) => {
  if (confirm('确定要删除此订单吗？删除后无法恢复。')) {
    orders.value = orders.value.filter(order => order.id !== orderId)
    saveOrders()
    alert('订单删除成功！')
  }
}

const loadOrders = () => {
  const savedOrders = localStorage.getItem('qingbook-orders')
  if (savedOrders) {
    try {
      const parsedOrders = JSON.parse(savedOrders)
      if (Array.isArray(parsedOrders) && parsedOrders.length > 0) {
        orders.value = parsedOrders
        return
      }
    } catch (error) {
      console.error('解析订单数据失败:', error)
    }
  }
  orders.value = []
}

const formatDate = (timestamp) => {
  const date = new Date(timestamp)
  return `${date.getFullYear()}-${(date.getMonth() + 1).toString().padStart(2, '0')}-${date.getDate().toString().padStart(2, '0')} ${date.getHours().toString().padStart(2, '0')}:${date.getMinutes().toString().padStart(2, '0')}`
}

const getStatusText = (status) => {
  const statusMap = {
    'pending_payment': '待付款',
    'pending_shipment': '待发货',
    'pending_receipt': '待收货',
    'completed': '已完成',
    'cancelled': '已取消',
    'refunded': '已退款',
    'returning': '退货中'
  }
  return statusMap[status] || '未知状态'
}

const getStatusClass = (status) => {
  return `status-${status}`
}

const confirmReceipt = (orderId) => {
  const order = orders.value.find(o => o.id === orderId)
  if (order) {
    order.status = 'completed'
    saveOrders()
    alert('确认收货成功！')
  }
}

const applyAfterSales = (orderId) => {
  currentOrderId.value = orderId
  showAfterSalesModal.value = true
}

const buyAgain = (order) => {
  const savedCart = localStorage.getItem('qingbook-cart')
  const cartItems = savedCart ? JSON.parse(savedCart) : []
  order.items.forEach(item => {
    const existingItem = cartItems.find(cartItem => cartItem.id === item.id)
    if (existingItem) {
      existingItem.quantity += item.quantity
    } else {
      cartItems.push({ ...item, selected: true })
    }
  })
  localStorage.setItem('qingbook-cart', JSON.stringify(cartItems))
  goToCart()
}

const cancelOrder = (orderId) => {
  if (confirm('确定要取消此订单吗？')) {
    const order = orders.value.find(o => o.id === orderId)
    if (order) {
      order.status = 'cancelled'
      saveOrders()
      alert('订单已取消')
    }
  }
}

const handleRefund = () => {
  if (currentOrderId.value) {
    const order = orders.value.find(o => o.id === currentOrderId.value)
    if (order) {
      order.status = 'refunded'
      saveOrders()
      alert('退款申请已提交')
      showAfterSalesModal.value = false
    }
  }
}

const handleReturnRefund = () => {
  if (currentOrderId.value) {
    const order = orders.value.find(o => o.id === currentOrderId.value)
    if (order) {
      order.status = 'returning'
      saveOrders()
      alert('退货退款申请已提交')
      showAfterSalesModal.value = false
    }
  }
}

const saveOrders = () => {
  localStorage.setItem('qingbook-orders', JSON.stringify(orders.value))
}

const goToHome = () => {
  router.push('/shop')
}

const goToCart = () => {
  router.push('/shopcart')
}
</script>

<style scoped>
.orders-container {
  min-height: 100vh;
  background-color: #f5f5f5;
}

.delete-order {
  color: #ff4444;
  border-color: #ff4444;
}

.delete-order:hover {
  opacity: 0.8;
}

/* 关键修改：售后模态框居中样式 */
.after-sales-modal {
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background-color: rgba(0, 0, 0, 0.5); /* 半透明遮罩 */
  z-index: 1000;
  display: flex; /* 关键：使用flex布局 */
  justify-content: center; /* 水平居中 */
  align-items: center; /* 垂直居中 */
}

.modal-overlay {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
}

.modal-content {
  background-color: #fff;
  padding: 24px;
  border-radius: 8px;
  min-width: 300px;
  max-width: 90%; /* 小屏幕适配 */
  box-shadow: 0 4px 16px rgba(0, 0, 0, 0.15);
  position: relative; /* 用于关闭按钮定位 */
}

.modal-content h3 {
  margin: 0 0 16px 0;
  color: #333;
  font-size: 18px;
}

.modal-content p {
  margin: 0 0 20px 0;
  color: #666;
  font-size: 14px;
}

.modal-actions {
  display: flex;
  flex-direction: column;
  gap: 12px;
  margin-bottom: 16px;
}

.modal-btn {
  padding: 10px;
  border: none;
  border-radius: 4px;
  cursor: pointer;
  font-size: 16px;
  transition: opacity 0.2s;
}

.modal-btn:hover {
  opacity: 0.8;
}

.refund {
  background-color: #00b4ac;
  color: #fff;
}

.return-refund {
  background-color: #ff6b6b;
  color: #fff;
}

.modal-close {
  position: absolute;
  top: 12px;
  right: 12px;
  padding: 4px 8px;
  background: transparent;
  border: none;
  font-size: 18px;
  color: #666;
  cursor: pointer;
}

/* 其他样式保持不变 */
.navbar {
  background-color: #fff;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
  padding: 0 20px;
  position: sticky;
  top: 0;
  z-index: 100;
}

.navbar-container {
  display: flex;
  align-items: center;
  max-width: 1200px;
  margin: 0 auto;
  height: 60px;
}

.logo {
  font-size: 20px;
  font-weight: bold;
  color: #00b4ac;
  margin-right: auto;
  padding: 0 15px;
  cursor: pointer;
  user-select: none;
}

.nav-menu {
  display: flex;
  list-style: none;
  height: 100%;
}

.nav-item {
  display: flex;
  align-items: center;
  padding: 0 15px;
  cursor: pointer;
  height: 100%;
  transition: all 0.3s ease;
  position: relative;
}

.nav-item:hover {
  color: #00b4ac;
  background-color: rgba(0, 180, 172, 0.1);
}

.nav-item.active {
  color: #00b4ac;
  border-bottom: 2px solid #00b4ac;
}

.avatar {
  width: 40px;
  height: 40px;
  border-radius: 50%;
  object-fit: cover;
}

.orders-content {
  max-width: 1200px;
  margin: 20px auto;
  padding: 0 20px;
}

.orders-header {
  background-color: #fff;
  padding: 20px;
  border-radius: 8px;
  margin-bottom: 20px;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.orders-header h2 {
  margin: 0;
  color: #333;
}

.order-filter {
  display: flex;
  gap: 10px;
}

.filter-btn {
  padding: 8px 16px;
  border: 1px solid #ddd;
  background-color: #fff;
  border-radius: 4px;
  cursor: pointer;
  transition: all 0.3s;
}

.filter-btn.active {
  background-color: #00b4ac;
  color: #fff;
  border-color: #00b4ac;
}

.filter-btn:hover:not(.active) {
  border-color: #00b4ac;
  color: #00b4ac;
}

.orders-list {
  display: flex;
  flex-direction: column;
  gap: 20px;
}

.order-item {
  background-color: #fff;
  border-radius: 8px;
  padding: 20px;
}

.order-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 15px;
  padding-bottom: 15px;
  border-bottom: 1px solid #eee;
}

.order-info {
  display: flex;
  flex-direction: column;
  gap: 5px;
}

.order-time, .order-id, .shop-name {
  font-size: 14px;
  color: #666;
}

.order-status span {
  padding: 4px 8px;
  border-radius: 4px;
  font-size: 14px;
}

.status-pending_payment {
  background-color: #fff8e6;
  color: #f57c00;
}

.status-pending_shipment {
  background-color: #e3f2fd;
  color: #1976d2;
}

.status-pending_receipt {
  background-color: #e8f5e9;
  color: #388e3c;
}

.status-completed {
  background-color: #f5f5f5;
  color: #757575;
}

.status-cancelled {
  background-color: #ffebee;
  color: #d32f2f;
}

.order-goods {
  margin-bottom: 15px;
}

.goods-item {
  display: flex;
  align-items: center;
  padding: 10px 0;
  border-bottom: 1px solid #f5f5f5;
}

.goods-item:last-child {
  border-bottom: none;
}

.goods-image {
  width: 80px;
  height: 80px;
  margin-right: 15px;
  background-color: #f9f9f9;
  border-radius: 6px;
  display: flex;
  align-items: center;
  justify-content: center;
}

.goods-image img {
  max-width: 100%;
  max-height: 100%;
  object-fit: contain;
}

.goods-info {
  flex: 1;
  margin-right: 15px;
}

.goods-title {
  margin: 0 0 8px 0;
  font-size: 16px;
  font-weight: bold;
  color: #333;
}

.goods-specs, .goods-color {
  margin: 0 0 5px 0;
  font-size: 14px;
  color: #666;
}

.goods-price {
  text-align: right;
}

.price-quantity {
  display: flex;
  flex-direction: column;
  align-items: flex-end;
  margin-bottom: 5px;
}

.current-price {
  font-size: 16px;
  font-weight: bold;
  color: #ff6b6b;
}

.quantity {
  font-size: 14px;
  color: #999;
}

.total-price {
  font-size: 16px;
  font-weight: bold;
  color: #ff6b6b;
}

.order-footer {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-top: 15px;
  padding-top: 15px;
  border-top: 1px solid #eee;
}

.order-total {
  font-size: 16px;
}

.total-amount {
  font-weight: bold;
  color: #ff6b6b;
  font-size: 18px;
}

.order-actions {
  display: flex;
  gap: 10px;
}

.action-btn {
  padding: 6px 12px;
  border: 1px solid #ddd;
  background-color: #fff;
  border-radius: 4px;
  cursor: pointer;
  font-size: 14px;
  transition: all 0.3s;
}

.action-btn:hover {
  opacity: 0.8;
}

.confirm-receipt {
  color: #00b4ac;
  border-color: #00b4ac;
}

.after-sales {
  color: #ff6b6b;
  border-color: #ff6b6b;
}

.buy-again {
  color: #00b4ac;
  border-color: #00b4ac;
}

.cancel-order {
  color: #999;
  border-color: #999;
}

.express-info {
  margin-top: 15px;
  padding: 15px;
  background-color: #f9f9f9;
  border-radius: 4px;
}

.express-info h4 {
  margin: 0 0 10px 0;
  color: #333;
  font-size: 16px;
}

.express-details p {
  margin: 5px 0;
  font-size: 14px;
  color: #666;
}

.empty-orders {
  text-align: center;
  padding: 60px 20px;
  background-color: #fff;
  border-radius: 8px;
}

.empty-icon {
  font-size: 80px;
  margin-bottom: 20px;
}

.empty-orders h3 {
  margin: 0 0 10px 0;
  color: #333;
}

.empty-orders p {
  color: #666;
  margin-bottom: 30px;
}

.go-shopping-btn {
  padding: 12px 30px;
  background-color: #00b4ac;
  color: #fff;
  border: none;
  border-radius: 4px;
  font-size: 16px;
  cursor: pointer;
  transition: background-color 0.3s;
}

.go-shopping-btn:hover {
  background-color: #00857d;
}

@media (max-width: 768px) {
  .orders-header {
    flex-direction: column;
    align-items: flex-start;
    gap: 15px;
  }

  .order-header {
    flex-direction: column;
    align-items: flex-start;
    gap: 10px;
  }

  .goods-item {
    flex-direction: column;
    align-items: flex-start;
  }

  .goods-image {
    margin-bottom: 15px;
  }

  .goods-info {
    margin-right: 0;
    margin-bottom: 15px;
  }

  .goods-price {
    align-self: flex-end;
  }

  .order-footer {
    flex-direction: column;
    align-items: flex-start;
    gap: 15px;
  }

  .order-actions {
    align-self: flex-end;
  }
}
</style>